<template>
  <div class="container">
      <div style="margin: 0 auto">
        <div class="bg">
          <div style="width: 100%">
            <div class="titleName">文件菜单</div>
            <div>
              <div class="queryTop"></div>
              <div class="listShow">
                <div class="showTree">
                  <el-card style="height:700px;overflow: auto;width:400px;">
                    <div style="display: flex;justify-content: space-between">
                      <div>
                        资源文件/目录
                      </div>
                      <div>
                        <i @click="reset()" style="margin-left: 30px" class="el-icon-refresh"></i>
                      </div>
                    </div>
                    <hr/>
                    <el-tree
                      :data="listChird"
                      ref="tree"
                      :props="defaultProps"
                      accordion
                      :highlight-current="true"
                      :expand-on-click-node="false"
                      node-key="id"
                      :current-node-key="queryParams.treeId"
                      default-expand-all
                      @node-click="handleNodeClick"
                    >
                        <span slot-scope="{ node, data }">
                            <span  :title="node.label">{{ node.label }}</span>
                          <span style="margin-left: 20px">
                            <el-button
                              type="text"
                              size="mini"
                              @click="() => editBizFolder(node,'add')">
                                <i class="el-icon-folder-add"></i>
                            </el-button>
                            <el-button
                              type="text"
                              size="mini"
                              @click="() => upFile(node)">
                                <i class="el-icon-upload2"></i>
                            </el-button>
                            <el-button
                              type="text"
                              size="mini"
                              @click="() => editBizFolder(node,'edit')">
                                <i class="el-icon-edit"></i>
                            </el-button>
                            <el-button
                              type="text"
                              size="mini"
                              v-if="data.PId!=0"
                              @click="() => remove(node, data)">
                             <i class="el-icon-delete"></i>
                            </el-button>
                          </span>
                        </span>
                    </el-tree>
                  </el-card>
                </div>
                <div class="showTable">
                  <el-card style="height:700px">
                    <el-table
                      :data="tableData"
                      height="600"
                      style="width: 100%">
                      <el-table-column
                        prop="fileRealname"
                        label="文件名称"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="insertTime"
                        label="创建时间"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="uploadUser"
                        label="操作人">
                      </el-table-column>
                      <el-table-column
                        label="操作"
                      >
                        <template slot-scope="scope">
                          <el-button @click="handleDelClick(scope.row)" type="text" size="small">删除</el-button>
                          <el-button @click="downloadEvt(scope.row)" type="text" size="small">下载</el-button>
                          <el-button @click="details(scope.row)" type="text" size="small">详情</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div style="margin: 10px auto 0">
                      <pagination
                        v-show="total > 0"
                        :total="total"
                        :page.sync="queryParams.current"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getstep"
                        :page-sizes="[10, 20, 30, 40]"
                      />
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
            <div>
              <el-dialog
                :title="title"
                :visible.sync="centerDialogVisible"
                width="800px"
                append-to-body
                center
                @close="DialogVisibleQX('ruleForm')">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="节点名称：" prop="keyName">
                    <el-input v-model="ruleForm.keyName" maxlength="10"></el-input>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                      <el-button @click="DialogVisibleQX('ruleForm')">取 消</el-button>
                      <el-button type="primary" @click="titleType=='add'?addDialog('ruleForm'):editDialog('ruleForm')">确 定</el-button>
                </span>
              </el-dialog>
              <el-dialog :visible.sync="upOpen" width="400px" append-to-body>
                <el-upload
                  ref="upload"
                  :limit="1"
                  action="/api/FileOperation/uploadFileByFdsf"
                  :auto-upload="false"
                  :headers="headersToken"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :data="{treeId:queryParams.treeId}"
                  drag
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
                <div slot="footer" class="dialog-footer">
                  <el-button type="primary" @click="submitFileForm">确 定</el-button>
                  <el-button @click="upOpen = false">取 消</el-button>
                </div>
              </el-dialog>
            </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
    import {getFileTreeList,getFileTreeTableList,deleteFile,downloadFileByFdsf,addNodeFileTree,delNodeFileTree,editNodeFileTree} from "@/api/fileManagement";
    import Cookies from "js-cookie";
    export default {
        name: "index",
        data(){
            return{
                listChird:[],
                tableData:[],
                queryParams:{
                    treeId:'',
                    current: 1,
                    pageSize:10,
                },
                title:'添加节点',
                centerDialogVisible:false,
                defaultProps: {
                    children: 'childList',
                    label: 'title'
                },
                url:'',
                ruleForm:{
                    keyName:'',
                },
                titleType:'',
                rules: {
                    keyName: [
                        { required: true, message: '请输入节点名称', trigger: 'blur' },
                    ],
                },
                upOpen:false,
                // 设置上传的请求头部
                headersToken: { Authorization: "Bearer " + Cookies.get('Admin-Token')},
                total:0,
            }
        },
        methods:{
            handleNodeClick(data){
                    console.log(data,'---');
                    this.queryParams.treeId=data.id
                    this.getTableList(this.queryParams);
            },
            getTreeList(){
                getFileTreeList().then(res=>{
                    this.listChird=res.data;
                })
            },
            getTableList(data){
                getFileTreeTableList(data).then(res=>{
                    console.log(res,'++++')
                     this.tableData= res.data;
                    this.url = res.fileServerUrl;
                    this.total = res.total;
                })
            },
            //删除列表数据
            handleDelClick(data){

                this.$modal.confirm('是否确认删除').then(()=>{
                      return deleteFile({id:data.id})
                }).then(res=>{
                    this.$message.info(res.message)
                    this.getTableList(this.queryParams);
                    // this.getTreeList();
                })
                console.log(this.queryParams.treeId)
            },
            downloadEvt(data,type=''){

                console.log(data,'---')
                downloadFileByFdsf({id:data.id}).then(res=>{
                    if(this.urlpathThree=='pdf'){
                        type = "application/pdf;charset=UTF-8"
                    }else if(this.urlpathThree=='ocx'){
                        type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8"
                    }else if(this.urlpathThree=='png'){
                        type = "image/png;charset=UTF-8"
                    }else if(this.urlpathThree=='jpg' || this.urlpathThree=='jpeg'){
                        type = "image/image/jpeg;charset=UTF-8"
                    }else if(this.urlpathThree=='gif'){
                        type = "image/gif;charset=UTF-8"
                    }else if(this.urlpathThree=='doc'){
                        type = "application/msword;charset=UTF-8"
                    }else if(this.urlpathThree=='xls'){
                        type = "application/vnd.ms-excel;charset=UTF-8"
                    }else if(this.urlpathThree=='lsx'){
                        type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
                    }else if(this.urlpathThree=='ppt'){
                        type = "application/vnd.ms-powerpoint;charset=UTF-8"
                    }else if(this.urlpathThree=='ptx'){
                        type = "application/vnd.openxmlformats-officedocument.presentationml.presentation;charset=UTF-8"
                    }
                    let blob =new Blob([res],{type:type})
                    let aLink = document.createElement("a")
                    aLink.download=data.fileRealname;
                    aLink.href=window.URL.createObjectURL(blob)
                    aLink.click();
                })
            },
            //打开新增节点对话框
            append(node,data){
                console.log(node.data)
                // event.stopPropagation(); // 阻止冒泡给nodeClick
                this.centerDialogVisible=true;
                this.queryParams.treeId = data.id;

            },
            reset(){
                this.getTreeList()
            },
            closeDialog() {
                this.centerDialogVisible = false;
            },
            //新增节点
            addDialog(formName){
                var formData = new FormData();
                formData.append("treeId", this.queryParams.treeId);
                formData.append("title", this.ruleForm.keyName);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        addNodeFileTree(formData).then(res=>{
                              if(res.addFlag==true){
                                  this.centerDialogVisible = false;
                                  this.$refs.tree.setCurrentKey(this.queryParams.treeId);
                                  this.getTreeList();
                              }
                        })
                    } else {
                        console.log('请输入节点名称');
                        return false;
                    }
                });
            },
            editDialog(formName){
                var formData = new FormData();
                formData.append("id", this.queryParams.treeId);
                formData.append("title", this.ruleForm.keyName);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        editNodeFileTree(formData).then(res=>{
                            this.centerDialogVisible = false;
                            this.$refs.tree.setCurrentKey(this.queryParams.treeId);
                            this.getTreeList();
                        })
                    } else {
                        console.log('请输入节点名称');
                        return false;
                    }
                });
            },
            //删除节点
            remove(node){
                console.log(this.queryParams.treeId,'+++++');
                event.stopPropagation(); // 阻止冒泡给nodeClick
                if(this.queryParams.treeId!=''){
                    delNodeFileTree({id:node.data.id}).then(res=>{
                        if(res.deleteFlag==true){
                            this.$message.info(res.message)
                            this.getTreeList();
                        }
                    })
                    console.log(this.queryParams.treeId,'[[[[')
                }else{
                    this.$message.error('请选中当前节点')
                }

            },
            editBizFolder(node,type){
                event.stopPropagation(); // 阻止冒泡给nodeClick
                const data = node.data;
                const parentData = node.parent.data;
                const title = type == "add" ? "新增目录" : "编辑目录";
                //...弹窗逻辑，保存后回调
                const refreshNode = type == "add" ? node : node.parent;
                // this.loadDataTree(refreshNode);　　//刷新节点
                // console.log(data,parentData,refreshNode)
                if(type == "add"){
                    this.titleType = 'add'
                    this.append(node,data);
                    this.ruleForm.keyName=''
                }else{
                    this.titleType = 'edit'
                    this.append(node,data);
                    this.ruleForm.keyName = data.title
                }
            },
            details(row){
                console.log(row)
                this.$router.push({path:'fileShow',query:{id:row.id}})
            },
            upFile(node){
                 this.queryParams.treeId=node.data.id;
                 this.upOpen=true;
                 this.$refs.upload.clearFiles();
            },
            handleFileUploadProgress(event, file, fileList,) {
                fileList=[];
                console.log(event,file,fileList)
                file.token = localStorage.getItem('Admin-Token');
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upOpen = false;
                this.$message.info(response.message)
                this.getTableList(this.queryParams);
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();


            },
            DialogVisibleQX(formName){
                this.$refs[formName].resetFields();
                this.centerDialogVisible = false;
            },
            getstep(){
                this.getTableList(this.queryParams);
            },
        },
        mounted() {
            this.getTreeList()
        }
    }
</script>

<style lang="scss" scoped>
  .container {
    height: calc(100vh - 84px);
    background:#eee;
    background-size: cover;
  }
  .bg {
    background: #fff;
    padding: 10px 20px;
    margin: 0 auto;
    min-height: calc(100vh - 84px);
    display: flex;
    justify-content:center;
  }

  .titleName{
    text-align: center;
    font-size: 23px;
    line-height: 60px;
    font-weight:600;
  }
  .fileList{
    height:700px;
    width:95%;
    li{
      line-height: 30px;
      cursor: pointer;
    }
  }
  .active {
    background: #e5e5e5;
  }
  .iframeWidth{
    width:100%;
    height:700px;

  }
  img{
    width:100%;
    height:650px;
  }
  .listShow{
    display: flex;
    flex-direction: row;
    .showTree{
      flex: 1;
      height:700px;
      width:400px;
    }
    .showTable{
      flex: 3;
      margin-left: 10px;
      height:700px
    }
    ::v-deep .el-tree{
      min-width:100%;
      display: inline-block;
    }
  }
  .span-ellipsis{
    width:10%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
